import io from 'socket.io-client'
import axios from 'axios'
const socket = io('ws://localhost:8000')
const SAVE_MESSAGE_DATA = 'SAVE_MESSAGE_DATA'
const ADD_MESSAGE_DATA = 'ADD_MESSAGE_DATA'
const UPDATE_MESSAGE_DATA = 'UPDATE_MESSAGE_DATA'
const DEFAULT = 'DEFAULT'
const RESET = 'RESET'

const initState = {
    messages: [],
    unReadCount: 0,
    code: -1,
}

export function chat(state={...initState}, action){
    const { payload } = action
    switch(action.type){
        case SAVE_MESSAGE_DATA:
            return { ...state, code: payload.code, messages: [...state.messages, ...payload.messages], unReadCount:
                payload.messages.filter( item => item.to === payload.userId && !item.read ).length
            }
        case ADD_MESSAGE_DATA:
            return { ...state, code: payload.code, messages: [...state.messages, ...payload.messages], unReadCount:
                state.unReadCount + ( payload.to === payload.userId ? 1 : 0 )
            }
        case UPDATE_MESSAGE_DATA:
            return { ...state, code: payload.code, messages: state.messages.map(item =>
                ({ ...item, read: item.from === payload.from ? true : item.read })),
                unReadCount: state.unReadCount - payload.num }
        case RESET:
            return { ...state, ...initState }
        default:
            return state
    }
}

export function receiveMsg(){
    return (dispatch, getState) => {
        socket.on('receiveMsg', (data) => {
            const { user: { user: { _id } } } = getState()
            const { from, to } = data
            if(from === _id || to === _id)
                dispatch({type: ADD_MESSAGE_DATA, payload: { ...data, userId: _id }})
            else
                dispatch({type: DEFAULT})
        })
    }
}

export function sendMsg(from, to, content){
    return dispatch => {
        socket.emit('sendMsg',{ from, to, content })
    }
}

export function getMessages(){
    return (dispatch, getState) => {
        axios.get('/chat/data')
            .then(res => {
                const { user: { user: { _id } } } = getState()
                dispatch({type: SAVE_MESSAGE_DATA, payload: { ...res.data, userId: _id }})
            })
    }
}

export function updateMessage(from){
    return dispatch => {
        axios.post('/chat/update', {from})
            .then(res => {
                dispatch({
                    type: UPDATE_MESSAGE_DATA,
                    payload: { ...res.data, from }
                })
            })
    }
}

export function chatReset(){
    return { type: RESET }
}